/* eslint-disable */
import React, { Component } from "react";

import Clipboard from 'clipboard';

import Banner from '../../components/Slide/index';
import ReachBottom from '../../components/ReachBottom';
import AdBlock from '../../components/AdBlock'

import Dialog from '../MyPackage/components/Dialog';
import Toast from '../MyPackage/components/Toast';
import InfiniteScroll from '../MyPackage/components/InfiniteScroll';

import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import weixinShare from '../../lib/weixinShare';

import wxUploadImage from './PhotoBack';

require('es6-promise').polyfill();

require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less');
require('./PickUp.less');

const PSIZE = 6;
const loader = <div className="loader">
    <i className="weui-loading"></i>
</div>;

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            order_id: Tools.getParams().order_id,
            isLoaded: false,
            have_news: false,   //我－－－是否展示小红点提示
            listType: Tools.getParams().list_type == 2 ? 'new_unpick' : 'unpick',   //列表类型(pick: 取件   send: 寄件)
            banner_data: [],//广告图
            partner_data: [],//合作商列表
            unpick_list: [],
            unpick_count: 0,
            tranship_list: [],
            tranship_count: 0,
            picked_list: [],
            picked_count: 0,
            confirm_order_id: 0,
            confirm_cabinet_code: 0,
            confirmCabinetDialog: false,
            current_unpick_page: 0,
            current_tranship_page: 0,
            current_picked_page: 0,
            tao_list: [],
            logis_id_list: [],

            cabinet_code: Tools.getParams().cabinet_code || sessionStorage.getItem('cabinet_code') || '',
            from: Tools.getParams().from,
            select_exp_code: '',        //  要查询的快递单号
            new_unpick_count: 0,
            new_unpick_list: [],
            new_current_unpick_page: 0,
            manageName: '',
        };
    }

    componentWillMount() {
        // 取url参数，wx_type
        window.localStorage.setItem('wx_type', Tools.getParams().wx_type === 'garden' ? Tools.getParams().wx_type : 'logis');
        // Tools.createCookie('wx_type', Tools.getParams().wx_type);
    }

    componentDidMount() {
        this.clearLocalStorage();

        new Clipboard('.right-btn');

        weixinShare.hideAll();
        this.recordPv();

        AJAX.request('get_tao_code', {}, data => {
            this.setState({
                tao_list: data.body ? data.body.split(',') : [],
            });
        });

        AJAX.request('get_logis_id', {}, data => {
            this.setState({
                logis_id_list: data.body ? data.body.split(',').map(id => Number(id)) : [],
            });
        });

        const manageNameInSession = sessionStorage.getItem('manageData');
        //  客户管理-根据手机号查询
        if (!manageNameInSession) {
            AJAX.request('queryByPhone', {}, data => {
                if (data.body.id > 0) {
                    sessionStorage.setItem('manageData', JSON.stringify(data.body));
                }
            });
        }

        // 扫码查询快递
        if (Tools.getParams().cabinet_code || Tools.getParams().from) {
            Tools.getParams().cabinet_code && (sessionStorage.setItem('cabinet_code', Tools.getParams().cabinet_code));
            const callback = () => {
                this.selectOrder();
            }
            if (!manageNameInSession) {
                this.whiteManageName('', callback);
            } else {
                this.selectOrder();
            }
        }

        // 扫描驿站码获取id
        if (Tools.getParams().station_id) {
            Tools.getParams().station_id && (sessionStorage.setItem('station_id', Tools.getParams().station_id));
            // 直接调用相机API
            wxUploadImage();
        }



        this.fetchHome();
        this.fetchList({ type: 'unpick' });
        this.fetchList({ type: 'new_unpick' });
    }

    recordPv() {
        AJAX.appendBaiduAnalysis(() => {
            var _hmt = window._hmt || [];
            _hmt.push(['_trackEvent', 'page', 'view', '取快递首页']);
        });
    }

    /**
     * 
     * @param {*} advertId 广告id
     * @param {*} type 2: 点击; 3: 曝光; 4: 跳转;
     */
    fetchSaveAdvert(advertId, type) {
        const params = {
            advertId: advertId,
            type: type,
        };
        AJAX.request('advertSave', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
    }

    fetchHome() {
        const params = {
            page: 1,
            psize: PSIZE,
        }, that = this;

        AJAX.request('home', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                const bannerList = body.banner_list || [];
                const partnetList = body.text_ad_list || [];
                const has_new_user_info = body.has_new_user_info !== 0;   // "has_new_user_info": 0/1 # 是否有用户的新消息(0:没有，1:有)

                //定义广告数组
                const bannerArray = bannerList.reduce((origin, item) => {
                    origin.push({
                        id: item.id,
                        link: item.url,
                        src: item.img
                    });
                    that.fetchSaveAdvert(item.id, 3);
                    return origin;
                }, []);

                this.setState({
                    isLoaded: true,//加载成功
                    have_news: has_new_user_info, // "has_new_user_info": 0/1 # 是否有用户的新消息(0:没有，1:有)
                    banner_data: bannerArray,
                    partner_data: partnetList, // 合作商列表
                })
            }
        });
    }

    clearLocalStorage() {
        // 清除寄件页面localStorage
        window.localStorage.removeItem("logisInfo_x");  //寄件站点信息
        window.localStorage.removeItem("sender_addr_x");  //寄件人信息
        window.localStorage.removeItem("receiverData_x");  //收件人信息
        window.localStorage.removeItem("sendingPackageHeader_defaultExpress_x");  //默认快递公司
        window.localStorage.removeItem("sendingPackageHeader_goodName_x");  //已选物品名称
        window.localStorage.removeItem("sendingPackageHeader_goodWeight_x");  //已选物品重量
        window.localStorage.removeItem("sendingPackageHeader_expressInfo_x");  //已选快递公司
        window.localStorage.removeItem("sendingPackageHeader_payType_x");  //已选付款方式
        window.localStorage.removeItem("sendingPackageHeader_vipCode_x");  //已填写VIP卡号
        // 清除查询快递页面localStorage
        window.localStorage.removeItem("checkPackage_express_info_x");  //已选快递公司信息
        window.localStorage.removeItem("PackageTracker_package_id_x");  //快递单号信息
        // 清除柜体寄件
        window.localStorage.removeItem("CabinetSendingInfo_x");  //已选快递柜信息
        window.localStorage.removeItem("selected_express_company");  //已选快递公司信息
    }

    isPending(type) {
        switch (type) {
            case 'unpick':
                if (this.unpick_pending) return true;
                break;
            case 'new_unpick':
                if (this.new_unpick_pending) return true;
                break;
            case 'tranship':
                if (this.tranship_pending) return true;
                break;
            case 'picked':
                if (this.picked_pending) return true;
                break;
        }
        return false
    }

    //列表选择
    handleChooseList(type) {
        const {
            listType,
            tranship_list,
            picked_list,
        } = this.state;

        if (listType === type) return;

        this.setState({ listType: type });

        if (this.isPending(type)) return;
        // if (type === 'new_unpick') {
        //     this.fetchList({ type: 'new_unpick' });
        // }
        if (type === 'tranship' && tranship_list === null) {
            this.fetchList({ type: 'tranship' });
        } else if (type === 'picked' && picked_list === null) {
            this.fetchList({ type: 'picked' });
        }
    }

    fetchList = ({ page_num = 1, type, isLoad = false }) => {

        const params = type !== 'new_unpick' ? {
            page: page_num,
            psize: PSIZE,
        } : {
            startTime: Tools.getDate(),
            pageIndex: page_num,
            pageSize: PSIZE,
        };

        if (this.isPending(type) && !isLoad) return;

        let req_key = null;
        switch (type) {
            case 'unpick':
                req_key = 'logis_unpick_list';
                this.unpick_pending = true;
                break;
            case 'new_unpick':
                req_key = 'new_unpick_list';
                this.new_unpick_pending = true;
                break;
            case 'tranship':
                req_key = 'tranship_list';
                this.tranship_pending = true;
                break;
            case 'picked':
                req_key = 'picked_list';
                this.picked_pending = true;
                break;
        }

        return new Promise((resolve, reject) => {
            AJAX.request(req_key, params, (data) => {
                if (data.code === 0) {
                    let list = data.body.list || []
                    if (list.length > 0) {
                        switch (type) {
                            case 'unpick':
                                let unpick_list = this.translateUnreceivedPackages(list)
                                if (page_num > 1) {
                                    unpick_list = [...this.state.unpick_list, ...unpick_list];
                                }
                                this.setState({
                                    unpick_list,
                                    unpick_count: data.body.count,
                                    current_unpick_page: page_num,
                                });
                                this.unpick_pending = false;
                                break;
                            case 'new_unpick':
                                let new_unpick_list = list;
                                if (page_num > 1) {
                                    new_unpick_list = [...this.state.new_unpick_list, ...new_unpick_list];
                                }
                                this.setState({
                                    new_unpick_list,
                                    new_unpick_count: data.body.count,
                                    new_current_unpick_page: page_num,
                                })
                                this.new_unpick_pending = false;
                                break;
                            case 'tranship':
                                let tranship_list = this.translateTranshipOrders(list)
                                if (page_num > 1) {
                                    tranship_list = [...this.state.tranship_list, ...tranship_list];
                                }
                                this.setState({
                                    tranship_list,
                                    tranship_count: tranship_list.length,
                                    current_tranship_page: page_num,
                                })
                                this.tranship_pending = false;
                                break;
                            case 'picked':
                                let picked_list = this.translatePickedList(list)
                                if (page_num > 1) {
                                    picked_list = [...this.state.picked_list, ...picked_list];
                                }
                                this.setState({
                                    picked_list,
                                    picked_count: data.body.count,
                                    current_picked_page: page_num,
                                })
                                this.picked_pending = false;
                                break;
                        }
                    } else if (page_num == 1 && list.length === 0) {
                        switch (type) {
                            case 'unpick':
                                this.setState({
                                    unpick_list: [],
                                    unpick_count: data.body.count,
                                    current_unpick_page: page_num,
                                })
                                this.unpick_pending = false;
                                break;
                            case 'new_unpick':
                                this.setState({
                                    new_unpick_list: [],
                                    new_unpick_count: data.body.count,
                                    new_current_unpick_page: page_num,
                                })
                                this.new_unpick_pending = false;
                                break;
                        }
                    }
                    else {
                        this.setState({ page: page_num - 1 })
                    }
                    resolve();
                }
                reject();
            });
        })
    }

    // 待收包裹
    translateUnreceivedPackages(list = []) {
        return list.map((item) => {
            let label_name, label_number
            if (item.storage_info.type === 1) {
                // 柜体，有箱门号
                label_name = '箱门号：';
                label_number = item.storage_info.cell_code;
            } else if (item.storage_info.type === 2) {
                // 货架，有取件号
                label_name = '取件码：';
                label_number = item.storage_info.cell_code;
            } else if (item.storage_info.type === 3) {
                // 地堆
                label_name = '取件码：';
                label_number = item.storage_info.pkg_num;
            } else if (item.storage_info.type === 4) {
                // 驿站
                label_name = '取件码：';
                label_number = item.storage_info.cell_code;
            } else if (item.storage_info.type === 5) {
                // 新货架
                label_name = '';
                label_number = item.storage_info.cell_code;
            }
            return {
                order_id: item.id,
                type: item.storage_info.type,
                order_type: item.order_type,
                title: item.storage_info.addr,
                express_company: item.exp_name,
                express_number: item.exp_code,
                exp_img: item.exp_img,
                show_time: item.wait_time,
                label_name,
                label_number,
                need_pay: item.need_pay,
                pay_amount: item.pay_amount || 0,    //  取件需要支付金额
                open_code: item.open_code,      // 取件码
                is_agenting: item.is_agenting,
                settle_amount: item.settle_amount,
                balance: item.balance,
                cabinet_code: item.storage_info.code,
                scan_confirm: item.storage_info.scan_confirm,
                is_agenting: item.is_agenting,
                logis_id: item.logis_info.id,
                isStationPickup: item.storage_info.isStationPickup,  // TODO 驿站是否开启自主取件 1:开启; 2: 关闭
            };
        })
    }

    // 未投包裹
    translateTranshipOrders = (list = []) => {
        return list.map((item) => {
            return {
                order_id: item.id,
                title: '物流中心：' + item.logis_info.name,
                order_type: item.order_type,
                express_company: item.express_info.name,
                express_number: item.exp_code,
                show_time: item.create_time,
                exp_img: item.express_info.img,
            };
        })
    }

    // 已取包裹
    translatePickedList(list = []) {
        return list.map((item) => ({
            order_id: item.id,
            order_type: item.order_type,
            state: item.state,
            title: item.storage_info.addr,
            express_company: item.exp_name,
            express_number: item.exp_code,
            exp_img: item.exp_img,
            receive_time: item.out_time,
            show_time: item.out_time,
        }));
    }

    // 获取数据列表
    makeList = ({ list = [], count, current_page, type }) => {
        const loadMore_func = this.fetchList({ page_num: current_page + 1, type });
        let has_more = false;

        //成功返回数据才 render
        const content = this.listTemplate(list, type)

        //判断是否需要加载更多
        if (current_page * PSIZE < count) {
            has_more = true;
        } else {
            has_more = false;
        }

        const titleMap = {
            unpick: '未取',
            tranship: '未投',
            picked: '已取',
        };

        const infi_content = (
            <InfiniteScroll
                threshold={15}
                loadMore={loadMore_func}
                hasMore={has_more}
                loader={loader}>
                {content}
            </InfiniteScroll>
        );

        return count === 0
            ? (
                <div>
                    <div className="empty-box">
                        <img src={'https://wechat.jinlb.cn/assets/images/icon-empty.png'} alt="" />
                        <div>暂无{titleMap[type]}包裹</div>
                    </div>

                    <AdBlock type="3" />
                </div>
            )
            : infi_content
    }

    /**
     * 找人代收
     */
    handleFriendToPickup = (id, e) => {
        e.stopPropagation();
        const { unpick_list, logis_id_list } = this.state;
        const order = unpick_list.find(item => item.order_id == id);

        if (order.is_agenting === 1) {
            Dialog.info({
                title: '',
                content: '快递在代收中...',
                okText: '确认',
                cancelText: '取消',
            })
        } else {
            // 首先判断物流中心是否开通无人车下单
            // return window.location.href = `./UnmannedCar?order_id=${id}&logis_id=${order.logis_id}`;
            if (!!order.logis_id) {

                AJAX.request('check_service', { logisId: order.logis_id }, data => {
                    const body = data.body;
                    if (body) {
                        window.location.href = `./UnmannedCar?order_id=${id}&logis_id=${order.logis_id}&price=${body.price}`;
                    } else if (logis_id_list.includes(order.logis_id)) {
                        window.location.href = 'http://m.daosu.jinlinbao.com/#/home';
                    } else {
                        order.type === 1 ? window.location.href = `./ChooseOtherReceiver?order_id=${id}` : Toast.warn({
                            content: '暂未开通该功能',
                        });
                    }
                });
            } else {
                order.type === 1 ? window.location.href = `./ChooseOtherReceiver?order_id=${id}` : Toast.warn({
                    content: '暂未开通该功能',
                });
            }


        }
    }

    /**
     * 一键开箱
     */
    handlePickup = (id, e) => {
        e.stopPropagation();

        const { unpick_list } = this.state;
        const order = unpick_list.find(item => item.order_id == id);

        if (order.is_agenting === 1) return;

        if (order.scan_confirm) {
            this.setState({
                confirmCabinetDialog: true,
                confirm_order_id: id,
                confirm_cabinet_code: order.cabinet_code,
            });
        } else {
            AJAX.request('need_pay', { order_id: id }, data => {
                if (data.code === 0) {
                    Dialog.confirm({
                        title: '',
                        content: '请核对当前地址或柜体编号与取件信息是否一致，否则由此带来的损失由您负责。',
                        okText: '仍要开箱',
                        cancelText: '取消',
                        onOK: () => {
                            window.location.href = `./OpenBoxFinal?order_id=${id}`
                        },
                    });
                } else {
                    window.location.href = `./PickUpDetailOne?order_id=${id}`;
                }
            });
        }
    }

    /**
     * 
     * @param {*} id 
     * 新驿站 一键开箱 
     */
    handleNewPickup = (order) => {

        const { new_unpick_count } = this.state;

        if (order.isScanCode === 1) {
            this.setState({
                confirmCabinetDialog: true,
                confirm_order_id: order.orderId,
                confirm_cabinet_code: order.cabCode,
            });
        }
        else {
            AJAX.request('getCharge', { orderId: order.orderId }, data => {
                if (data.code === 0 && data.body.amount === 0) {
                    Dialog.confirm({
                        title: '',
                        content: '检测到您当前位置与柜体距离较远！请核对您的位置与柜体位置是否一致，否则由此带来的损失由您负责。',
                        okText: '仍要开箱',
                        cancelText: '取消',
                        onOK: () => {
                            window.location.href = `./OpenBoxNewFinal?order_id=${order.orderId}`
                        },
                    });
                } else {
                    window.location.href = `./NewPickUpDetail?order_id=${order.orderId}&count=${new_unpick_count}&order_type=${order.storageType}`;
                }
            });
        }

    }

    /**
     * 新驿站确认取件
     */
    handleNewSelfPickup = (order) => {
        const that = this;
        Dialog.confirm({
            title: '提示',
            htmlContent: (<div style={{ padding: '15px' }}>
                <div style={{ color: '#999', marginBottom: '10px' }}>请确认是否已取走</div>
                <div style={{ color: 'red' }}>注意: 确认取走后，该包裹视为本人取走。</div>
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOK: () => {
                // 自助取件
                AJAX.request('new_pickUp', { orderId: order.orderId, stationId: order.stationId }, result => {
                    if (!result.body.to_pickup_count || result.body.to_pickup_count < 1) {
                        AJAX.request('get_advert_detail', { type: 6 }, (data) => {
                            that.fetchSaveAdvert(data.body.id, 4);
                            if (data.code == 0) {
                                var advert_url = data.body.url;
                                window.location.href = advert_url;
                            }
                        })
                    } else {
                        that.fetchList({ type: 'new_unpick', isLoad: true });
                    }
                });
            },
        })
    }

    /**
     * 
     * @param {*} advertId 广告id
     * @param {*} type 2: 点击; 3: 曝光; 4: 跳转;
     */
    fetchSaveAdvert(advertId, type) {
        const params = {
            advertId: advertId,
            type: type,
        };
        AJAX.request('advertSave', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
    }

    /**
     * 确认取件
     */
    handleSelfHelpPickup = (id, e) => {
        e.stopPropagation();
        const that = this;
        Dialog.confirm({
            title: '提示',
            htmlContent: (<div style={{ padding: '15px' }}>
                <div style={{ color: '#999', marginBottom: '10px' }}>请确认是否已取走</div>
                <div style={{ color: 'red' }}>注意: 确认取走后，该包裹视为本人取走。</div>
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOK: () => {
                // 自助取件
                AJAX.request('fault_pickup', { order_ids: id }, result => {
                    // 只有当 待取件 为0时，再跳转广告
                    if (!result.body.to_pickup_count || result.body.to_pickup_count < 1) {
                        AJAX.request('get_advert_detail', { type: 6 }, (data) => {
                            that.fetchSaveAdvert(data.body.id, 4);
                            if (data.code == 0) {
                                var advert_url = data.body.url;
                                window.location.href = advert_url;
                            }
                        })
                    }
                    else {
                        that.fetchList({ type: 'unpick', isLoad: true });
                    }
                });
            },
        })
    }

    jumpNewUnPick(item) {
        const { new_unpick_count } = this.state;
        //  TODO: 暂时注释不跳转耳机页面
        if (new_unpick_count > -1) {
            window.location.href = `./NewPickUpDetail?order_id=${item.orderId}&count=${new_unpick_count}&order_type=${item.storageType}`;
        }
        else if (new_unpick_count > 1) {
            const url = item.storageType === 3 ? `./NewPickUpList?cabinet_id=${item.storagePid}&type=${item.storageType}` : `./NewPickUpList?station_id=${item.stationId}&type=${item.storageType}`;
            window.location.href = url;
        }
    }

    createExpressCardElem = (express, type) => {
        let time_label, handleEvent = null;
        switch (type) {
            case 'unpick':
                time_label = '等待时间';
                handleEvent = () => this.jumpRecipentDetail(express.order_id);
                break;
            case 'new_unpick':
                time_label = '等待时间';
                handleEvent = () => {
                    // 判断跳详情 还是 列表
                    this.jumpNewUnPick(express);
                };
                break;
            case 'tranship':
                time_label = '到校时间';
                break;
            case 'picked':
                time_label = '取件时间';
                handleEvent = () => this.jumpRecipentDetail(express.order_id, express.out_time);
                break;
        }

        const { tao_list } = this.state;
        const sign = Math.floor(Math.random() * tao_list.length);

        /**
         * 订单状态
            1、待核对手机号；2、待出库；3、已出库；4、已退回；5、待柜体响应；6待退回；7、移库中、8、已废弃
         */
        const new_ExpressCard = (
            <div key={express.orderId}
                className="express-card"
                onClick={handleEvent}>
                <div className="lux-d-f stationInfo">
                    <div className="lux-fz18 lux-c333 lux-fw-b wordOmit">
                        <img className="stationIcon" src="//wechat.jinlb.cn/assets/images/province.png" />
                        {express.storageType === 4 ? '暂存区(请联系门店人取件)' : express.addr}
                    </div>
                    <div className="time">{express.createTime}</div>
                </div>
                <div className="lux-d-f pickupInfo">
                    <div style={{ flex: 1 }}>
                        <div className="openCode">
                            <div>取件码: {express.openCode}</div>
                            {express.storageType === 3 && <div style={{ fontWeight: 500, fontSize: 16 }}>格口号: {express.cellDesc}</div>}
                        </div>
                        <div className="lux-d-f">
                            <img className="expressIcon" src={express.expressLogo} />
                            <div style={{ fontSize: 16 }}>{express.expressName} {express.expCode}</div>
                            <img className="copyIcon" src="//wechat.jinlb.cn/assets/images/detail-copy.png" onClick={(e) => {
                                e.stopPropagation();
                                e.nativeEvent.stopImmediatePropagation();
                                Tools.copyExpCode(express.expCode);
                            }} />
                        </div>
                    </div>
                    <div>
                        <img className="arrow-right" src="https://wechat.jinlb.cn/assets/images/icon-right-arrow.png" />
                    </div>
                </div>
                {express.storageType === 3 && <div className="button-box lux-d-f lux-ai-c">
                    <div className="lux-flex-1 lux-center">
                        <div
                            className={'right-btn button2'}
                            style={{ fontSize: 18, flex: 1, height: 42 }}
                            onClick={(e) => {
                                e.stopPropagation();
                                const manageNameInSession = sessionStorage.getItem('manageData');
                                const callback = () => {
                                    this.handleNewPickup(express);
                                }
                                if (!manageNameInSession) {
                                    this.whiteManageName(express.stationId, callback);
                                }
                                else {
                                    this.handleNewPickup(express)
                                }
                            }}
                        >
                            一键开箱
                        </div>
                    </div>
                </div>}
                {(!!(express.storageType < 3) && !!(express.isStationPickup === 1) && !(express.amount > 0 && express.isPaid === 0)) ? <div className="button-box lux-d-f lux-ai-c">
                    <div className="lux-flex-1 lux-center">
                        <div
                            className={'right-btn button2'}
                            style={{ fontSize: 18, flex: 1, height: 42 }}
                            onClick={(e) => {
                                e.stopPropagation();
                                const manageNameInSession = sessionStorage.getItem('manageData');
                                const callback = () => {
                                    this.handleNewPickup(express);
                                }
                                if (!manageNameInSession) {
                                    this.whiteManageName(express.stationId, callback);
                                }
                                else {
                                    this.handleNewSelfPickup(express)
                                }
                            }}
                        >
                            确认取走
                        </div>
                    </div>
                </div> : null}
            </div>
        );

        return type === 'new_unpick' ? new_ExpressCard : (
            <div
                key={express.id}
                className="express-card"
                onClick={handleEvent}
            >
                {
                    type === 'unpick' && express.type !== 1 && (
                        <div className="button-box-header lux-center lux-cffa600 lux-fz14 lux-fw-500">
                            请前往物流中心取件
                        </div>
                    )
                }
                <div className="lux-d-f lux-ai-c">
                    <div className="lux-miw48">
                        <img className="icon-company" src={express.exp_img} alt="" />
                    </div>
                    <div className="luxp-w80">
                        <div className="title wordOmit">
                            {express.title}
                        </div>
                        <div className="lux-mt6">
                            <span className="company">{express.express_company}</span>：<span className="expcode">{express.express_number}</span>
                        </div>
                        <div className="lux-mt6 lux-d-f lux-jc-sb">
                            <div className="lux-d-f lux-ai-c">
                                {
                                    type === 'unpick' && (
                                        <img className="icon-clock lux-mr6" src="https://wechat.jinlb.cn/assets/images/icon-clock.png" alt="" />
                                    )
                                }
                                <div>{time_label}：</div>
                                <div className="lux-cffa600">{express.show_time}</div>
                            </div>
                            {
                                type === 'unpick' && (
                                    <div className="lux-d-f lux-ai-c">
                                        <img className="icon-clock" src="https://wechat.jinlb.cn/assets/images/icon-door.png" alt="" />
                                        <div className="lux-ml6">{express.label_name}</div>
                                        <div className="lux-c38C71B">{express.label_number}</div>
                                    </div>
                                )
                            }
                        </div>
                    </div>

                </div>
                {
                    type === 'unpick' && express.type === 1 && (
                        <div className="button-box lux-d-f lux-ai-c">
                            <div className="lux-flex-1 lux-center">
                                <div
                                    className="button1"
                                    onClick={this.handleFriendToPickup.bind(this, express.order_id)}
                                >
                                    {express.is_agenting === 0 ? '快递代取' : '代取中...'}
                                </div>
                            </div>
                            <div className="right-line" />
                            <div className="lux-flex-1 lux-center">
                                <div
                                    className={express.is_agenting === 0 ? 'right-btn button2' : 'right-btn button3'}
                                    onClick={this.handlePickup.bind(this, express.order_id)}
                                    data-clipboard-text={tao_list[sign]}
                                >
                                    一键开箱
                                </div>
                            </div>
                        </div>
                    )
                }
                {
                    !!(type === 'unpick' && express.type !== 1 && !!(express.isStationPickup === 1) & +express.pay_amount === 0) && (
                        <div className="button-box lux-d-f lux-ai-c">
                            <div className="lux-flex-1 lux-center">
                                <div
                                    className="button1"
                                    onClick={this.handleFriendToPickup.bind(this, express.order_id)}
                                >
                                    快递代取
                                </div>
                            </div>
                            <div className="right-line" />
                            <div className="lux-flex-1 lux-center">

                                <div
                                    className="button2 right-btn"
                                    onClick={this.handleSelfHelpPickup.bind(this, express.order_id)}
                                >
                                    确认取走
                                </div>
                            </div>
                        </div>
                    )
                }

                {
                    type !== 'tranship' && (
                        <img className={`icon-arrow ${(type === 'unpick' && express.type !== 1) ? 'icon-arrow-header' : ''}`} src="https://wechat.jinlb.cn/assets/images/icon-right-arrow.png" alt="" />
                    )
                }

            </div>
        );
    }

    // 生成列表区域
    listTemplate = (list = [], type) => {
        if (list === null) {
            return <div className="noExpressBox">{loader}</div>;
        }

        return list.map(item => this.createExpressCardElem(item, type));
    }

    // 统计广告
    handleStatAd = (id, title, url) => {
        AJAX.request("stat_advert", { advert_id: id, action: 1 }, (data) => {

            // 统计
            this.fetchSaveAdvert(id, 2);

            if (url) {
                if (url.indexOf("http") === 0) {
                    window.location.href = url
                } else {
                    window.location.href = "//" + url
                }
            }
        });

        if (window._hmt) {
            var _hmt = window._hmt;
            _hmt.push(["_trackEvent", "page", "click", id, title]);
        } else {
            AJAX.appendBaiduAnalysis(() => {
                var _hmt = window._hmt;
                _hmt.push(["_trackEvent", "page", "click", id, title]);
            });
        }
    }

    //跳转收件详情
    jumpRecipentDetail(order_id, out_time) {
        let qs = `order_id=${order_id}`;
        if (out_time) {
            qs += `&out_time=${out_time}`;
        }

        const wx_type = window.localStorage.getItem('wx_type');
        window.location.href = `./PickUpDetail?${qs}&wx_type=${wx_type}`;
    }

    //跳转我的页面
    jumpToPersonal() {
        const wx_type = window.localStorage.getItem('wx_type');
        window.location.href = `./Personal?wx_type=${wx_type}`;
    }

    // 长度大于1加载轮播组件，否则输出图片
    makeBanner() {
        const { banner_data } = this.state;

        let content = null;
        if (banner_data.length === 0) {
            content = <img src="https://wechat.jinlb.cn/assets/images/noAd.png" alt="" />;
        } else if (banner_data.length === 1) {
            content = (
                <a href={banner_data[0].link}>
                    <img
                        src={banner_data[0].src}
                        onClick={this.handleStatAd.bind(this, banner_data[0].id, banner_data[0].title)}
                    />
                </a>
            );
        } else if (banner_data.length > 1) {
            content = <Banner handleStatAd={this.handleStatAd} opts={banner_data} />
        }
        return (
            <div className='banner'>
                {content}
            </div>);
    }

    makePackageList() {
        const {
            listType,
            unpick_list,
            unpick_count,
            new_unpick_list,
            new_unpick_count,
            new_current_unpick_page,
            current_unpick_page,
            tranship_list,
            tranship_count,
            current_tranship_page,
            picked_list,
            picked_count,
            current_picked_page,
        } = this.state;

        let list_content = null;

        switch (listType) {
            // 未取列表
            case 'unpick':
                list_content = this.makeList({
                    type: listType,
                    list: unpick_list,
                    count: unpick_count,
                    current_page: current_unpick_page,
                })
                break;
            // 新驿站 待取列表
            case 'new_unpick':
                list_content = this.makeList({
                    type: listType,
                    list: new_unpick_list,
                    count: new_unpick_count,
                    current_page: new_current_unpick_page,
                })
                break;
            // 未投列表
            case 'tranship':
                list_content = this.makeList({
                    type: listType,
                    list: tranship_list,
                    count: tranship_count,
                    current_page: current_tranship_page,
                })
                break;
            // 已取列表
            case 'picked':
                list_content = this.makeList({
                    type: listType,
                    list: picked_list,
                    count: picked_count,
                    current_page: current_picked_page,
                })
                break;
        }

        return (
            <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb70">
                <div className="tab-box lux-d-f lux-ai-b">
                    <div
                        className={listType == 'unpick' ? 'tab-checked' : 'tab new-unpickList'}
                        onClick={this.handleChooseList.bind(this, 'unpick')}
                    >
                        未取包裹
                        {unpick_count > 0 && <div className="bubble">{unpick_count}</div>}
                    </div>
                    <div
                        className={listType == 'new_unpick' ? 'tab-checked' : 'tab new-unpickList'}
                        onClick={this.handleChooseList.bind(this, 'new_unpick')}
                    >
                        待取包裹
                        {new_unpick_count > 0 && <div className="bubble">{new_unpick_count}</div>}
                    </div>
                    <div
                        className={listType == 'tranship' ? 'tab-checked' : 'tab new-unpickList'}
                        onClick={this.handleChooseList.bind(this, 'tranship')}
                    >
                        未投包裹

                        {tranship_count > 0 && <div className="bubble">{tranship_count}</div>}
                    </div>
                    <div
                        className={listType == 'picked' ? 'tab-checked' : 'tab'}
                        onClick={this.handleChooseList.bind(this, 'picked')}
                    >
                        已取包裹
                    </div>
                </div>
                {
                    tranship_count > 0 && <div className="prompt lux-pl10">工作人员正在处理您的包裹，请耐心等待取件通知...</div>
                }
                <div className="weui-panel__bd lux-mt10">
                    {list_content}
                </div>
            </div>
        )
    }

    makeNavBar(style) {
        const {
            have_news
        } = this.state;
        const wx_type = window.localStorage.getItem('wx_type')
        return (
            <div className="weui-tabbar" style={style}>
                <a href={`./PickUp?wx_type=${wx_type}`} className="weui-tabbar__item">
                    <img src="https://cdn2.jinlb.cn/pic/01/30/013010fa684c9158cdedd6f2f79f0a9c.png" alt=""
                        className="weui-tabbar__icon" />
                    <p className="weui-tabbar__label">首页</p>
                </a>
                <a href={`./Personal?wx_type=${wx_type}`} className="weui-tabbar__item">
                    <img src="https://cdn2.jinlb.cn/pic/24/0a/240a273fb9a0d8db3b63cd26a9829b05.png" alt=""
                        className="weui-tabbar__icon" />
                    {have_news ? <div className="red_dot"></div> : null}
                    <p className="weui-tabbar__label">我</p>
                </a>
            </div>);
    }

    hideConfirmCabinetDialog = () => {
        this.setState({ confirmCabinetDialog: false })
    }

    handleConfirmCabinet = e => {
        e.stopPropagation();

        const { confirm_order_id, confirm_cabinet_code, listType, new_unpick_count } = this.state;

        window.location.href = `./ConfirmCabinet?order_id=${confirm_order_id}&cabinet_code=${confirm_cabinet_code}&listType=${listType}&new_unpick_count=${new_unpick_count}`;
    }

    createConfirmCabinetDialogElem = () => (
        <div
            className="dialog-confirm"
            onClick={this.hideConfirmCabinetDialog}
        >
            <div className="dialog-box">
                <div className="dialog-content">
                    <div className="title">安全提示</div>
                    <div className="desc">为了您的包裹安全，请扫描柜体条码取件</div>
                    <img src="https://cdn2.jinlb.cn/pic/fd/14/fd1414a22495532596caa354efbd510f.png" />
                </div>
                <div
                    className="dialog-footer"
                    onClick={this.handleConfirmCabinet.bind(this)}
                >
                    扫描
                </div>
            </div>
        </div>
    );

    selectOrder = () => {
        const { cabinet_code } = this.state;
        Dialog.confirm({
            title: '查快递',
            htmlContent: (
                <div style={{ padding: '0 20px', margin: '15px 0' }}>
                    <div className="weui-cell weui-cell_active" style={{ border: '1px solid #cdcdcd' }}>
                        {/* <div className="weui-cell__hd"><span className="weui-label">快递单号/取件码</span></div> */}
                        <div className="weui-cell__bd weui-flex">
                            <input className="weui-input" type="text" maxLength={30} placeholder={cabinet_code ? "请输入快递单号/取件码" : "请输入快递单号"} onChange={(e) => {
                                this.setState({ select_exp_code: e.target.value });
                            }} />
                        </div>
                    </div>
                    <div style={{ margin: '15px 0', textAlign: 'left' }}>注意：仅可查询90天内未取走的包裹</div>
                </div>
            ),
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOK: () => {
                const { select_exp_code } = this.state;
                if (!this.state.select_exp_code) {
                    Toast.warn({
                        content: cabinet_code ? '请输入快递单号或取件码' : '请输入快递单号',
                    });
                    return;
                }
                const params = cabinet_code ? {
                    cabinet_code: cabinet_code,
                    exp_code: select_exp_code
                } : {
                    exp_code: select_exp_code
                }
                AJAX.request('order_by_expCode', params, data => {
                    if (data.code === 0) {
                        // 老系统跳转
                        if (data.body.system === 1) {
                            this.jumpRecipentDetail(data.body.id);
                        } else {
                            window.location.href = `./NewPickUpDetail?order_id=${data.body.orderId}&count=0&order_type=${data.body.storageType}`;
                        }
                    } else if (data.code === 15101) { // 订单不存在
                        this.setState({
                            isLoading: 3,
                        });
                    }
                });
            },
        })
    };

    /**
     * 
     * @param {*} id stationId
     * @param {*} success 点确定后成功回调
     */
    whiteManageName = (id, success) => {
        Dialog.confirm({
            title: '提示',
            htmlContent: (
                <div style={{ padding: '0 20px', margin: '15px 0' }}>
                    <div className="weui-cell weui-cell_active" style={{ border: '1px solid #cdcdcd' }}>
                        {/* <div className="weui-cell__hd"><span className="weui-label">快递单号/取件码</span></div> */}
                        <div className="weui-cell__bd weui-flex">
                            <input className="weui-input" type="text" maxLength={30} placeholder={"请输入收件人购物昵称"} onChange={(e) => {
                                this.setState({ manageName: e.target.value });
                            }} />
                        </div>
                    </div>
                    <div style={{ margin: '15px 0', textAlign: 'left', color: 'red' }}>提示: 为了您能及时收到取件通知,请准确填写收件人购物昵称</div>
                </div>
            ),
            content: '',
            okText: '下一步',
            cancelText: '取消',
            onOK: () => {
                const { manageName } = this.state;
                AJAX.request('manageRegister', {
                    name: manageName,
                    stationId: id,
                }, data => {
                    if (data.code === 0) {
                        sessionStorage.setItem('manageData', JSON.stringify({ name: manageName, stationId: id }));
                        success();
                    }
                });
            },
        })
    };

    render() {
        const {
            isLoaded,
            bottom,
            confirmCabinetDialog,
        } = this.state;

        if (!isLoaded) return null;

        // 广告
        const banner = this.makeBanner();
        // 快递列表
        const packageList = this.makePackageList();
        // 导航条
        const navbar = this.makeNavBar(style);

        const style = {
            position: bottom ? 'relative' : 'fixed',
        };

        return (
            <div className="weui-tab" style={{ height: confirmCabinetDialog ? '100%' : 'anto' }}>
                <div className="weui-tab__panel">
                    {banner}
                    {/* 查询按钮 */}
                    <div className="footer-btn-box" style={{ justifyContent: 'space-between' }}>
                        <button className="footer-btn fun-btn" onClick={() => {
                            const manageNameInSession = sessionStorage.getItem('manageData');
                            const callback = () => {
                                this.selectOrder();
                            }
                            if (!manageNameInSession) {
                                this.whiteManageName('', callback);
                            } else {
                                this.selectOrder();
                            }
                        }}>查快递 <i className="jiantou"></i></button>
                        <button className="footer-btn fun-btn" style={{ margin: '0 12px', background: 'linear-gradient(135deg, #0166FF 0%, #0167FF 100%)' }} onClick={() => {
                            Toast.warn({ content: '功能暂未上线' });
                        }}>寄快递 <i className="jiantou"></i></button>
                        <button className="footer-btn fun-btn" style={{ background: 'linear-gradient(135deg, #22C64D 0%, #23C74D 100%)' }} onClick={() => {
                            const stationId = sessionStorage.getItem('station_id');
                            // 判断是否扫码获取了驿站id
                            if (!stationId) {
                                return Toast.warn({ content: '请使用微信扫一扫功能，扫描拍照出库二维码' });
                            }
                            wxUploadImage();
                        }} >拍照出库 <i className="jiantou"></i></button>
                    </div>
                    {packageList}
                    <div className="lux-flex-1"></div>
                    <ReachBottom height="53" bottom={bottom} onBottom={(v) => { this.setState({ bottom: v }) }} />
                    {navbar}
                    <div className="weui-wrapper" style={style}></div>
                    {confirmCabinetDialog && this.createConfirmCabinetDialogElem()}
                </div>
            </div>
        );
    }
}

ReactDOM.render(<Home />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}
